package de.velvettear.squirrel.adapter;

import java.util.Vector;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import de.velvettear.squirrel.R;
import de.velvettear.squirrel.kernel.Contact;
import de.velvettear.squirrel.kernel.Statics;

public class ContactListAdapter extends ArrayAdapter {
	
private Context context;
	
	private Vector<Contact> contacts;
				
	public ContactListAdapter(Context context, int layout, int textViewResourceId, Vector<Contact> contacts) {
		super(context, layout, textViewResourceId, contacts);
		this.context = context;
		this.contacts = contacts;
	}
	
	@Override
	public int getCount() {
		return contacts.size();
	}

	@Override
	public Contact getItem(int position) {
		return contacts.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	public void updateContact(String name, String type, String mode, String status) {
		if (name.contains("@")) {
			name = name.substring(0,name.indexOf("@"));
		}
		for (Contact contact : contacts) {
			if (contact.m_sName.equals(name)) {
				contact.m_sType = type;
				contact.m_sMode = mode;
				contact.m_sStatus = status;
				notifyDataSetChanged();
			}
		}		
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup viewGroup) {
		ContactListViewHolder viewHolder;
		Contact contact = contacts.get(position);	
		if (convertView == null) {
			LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = inflater.inflate(R.layout.listview_contactlist, null);
			
			viewHolder = new ContactListViewHolder();
			
			viewHolder.iv_contact = (ImageView) convertView.findViewById(R.id.listview_contactlist_icon);
			viewHolder.tv_name = (TextView) convertView.findViewById(R.id.listview_contactlist_name);
			viewHolder.tv_status = (TextView) convertView.findViewById(R.id.listview_contactlist_status);
			viewHolder.tv_mode = (TextView) convertView.findViewById(R.id.listview_contactlist_mode);			
			
			convertView.setTag(viewHolder);
		} else {
			viewHolder = (ContactListViewHolder) convertView.getTag();
		}	
				
		viewHolder.tv_name.setText(contact.m_sAlias);
		
		if (contact.m_sStatus != null && contact.m_sStatus.length() > 0) {
			viewHolder.tv_status.setText(contact.m_sStatus);
			viewHolder.tv_status.setVisibility(View.VISIBLE);
		} else {
			viewHolder.tv_status.setVisibility(View.GONE);
		}
		
		viewHolder.tv_mode.setText(contact.m_sMode);
		
		return convertView;	
	}

	static class ContactListViewHolder {
		View convertView;
		ImageView iv_contact;
		TextView tv_name;
		TextView tv_status;
		TextView tv_mode;
	}
}
